/* TCP客户端 */

#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

using namespace std;

int main()
{   
    /* 1.创建侦听套接字
     * 2.发起连接
     * */
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        perror("socket");
        return 0;
    }
    
    struct sockaddr_in ser_addr;
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(38989);
    ser_addr.sin_addr.s_addr = inet_addr("0.0.0.0");    //服务端的IP
    
    int ret = connect(sockfd, (struct sockaddr*)&ser_addr, sizeof(ser_addr)) ;
    if(ret < 0)
    {
        perror("connect");
        return 0;
    }


    /* 循环处理
     * 3.发收数据
     * */
    while(1)
    {
        char buf[1024] = {0};
        
        cout << "please enter mas# ";
        fflush(stdout);
        cin >> buf;

        ssize_t send_size = send(sockfd, buf, strlen(buf), 0);    //发数据
        if(send_size < 0)
        {
            perror("send");
            continue;
        }
        
        memset(buf, '\0', sizeof(buf));
        ssize_t recv_size = recv(sockfd, buf, sizeof(buf), 0);    //收数据
        if(recv_size < 0)
        {
            continue;
        }
        else if(recv_size == 0)
        {
            printf("server shutdown !\n");
            break;
        }

        cout << buf << endl;
    }

    close(sockfd);
    return 0;
}
